import Vue from 'vue';
import Router from 'vue-router';
// nprogress 进度条
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import store from '../store';
import {getAction, postAction} from '../api/manage';
import { SysUserUrl, common, SysLoginUrl} from '../api/url'
import {notification} from 'ant-design-vue';


import { constantRouterMap, whiteRouterPath, loginRouterPath } from './router-constant-table';// 常量路由表
NProgress.configure({ showSpinner: false });

Vue.use(Router);

//Navigating to current location (XXX) is not allowed"的问题
const routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
};



let router = new Router({
  // mode: 'history',
  mode:'hash',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
});

// 生成菜单路由
function  generateChildRouters (data) {
  const routers = [];
  data.forEach(item=>{
    //判断是否生成路由
    if(item.routeFlag == 'FALSE'){
      return;
    }
    let config = null;
    let menu =  {
      path: item.path,
      name: item.name,
      redirect:item.redirect,
      component: resolve => {
        if(item.component.startsWith("components")){
          return require(['../components/'+item.component.substring("components".length+1)], resolve)
        }
        if(item.component.startsWith("views")){
          return require(['../views/'+item.component.substring("views".length+1)], resolve)
        }
        return require(['../views/exception/404'], resolve)
      },
      hidden:item.hidden,
      meta: {
        title:item.meta.title ,
        icon: item.meta.icon,
        url:item.meta.url,
        keepAlive:item.meta.keepAlive,
        config:config
      }
    };
    if (item.children && item.children.length > 0) {
      menu.children = [...generateChildRouters( item.children)];
    }
    routers.push(menu);
  });
  return routers
}
// 跳转到登录页
function toLogin(to,from, next) {
  store.commit("CLEAR_USER");
  let redirect = decodeURIComponent(from.query.redirect || to.path);
  // 跳转到登录也
  next({query: {redirect}, path:loginRouterPath});
}


// 增加路由
function addRouter(to, from,next){
  if((store.getters.token() && store.getters.permissionList() && store.getters.permissionList().length >0)
    || (!store.getters.token() && to.path==loginRouterPath)
  ){
    next();
    return;
  }else if(!store.getters.token() && to.path!=loginRouterPath){
    toLogin(to, from, next);
    return;
  }
  // 未获取到权限
  let userInfoUrl = SysUserUrl.getUserInfo;
  let permissionUrl = SysUserUrl.getPermission;
  getAction(userInfoUrl)
    .then(
      res=>{
        if(!res.success){
          toLogin(to,from, next);
          return;
        }
        // 设置当前用户信息
        store.commit("SET_INFO", res.result);
        // 获取权限
        getAction(permissionUrl)
          .then(res => {
            let permissionList = res.result.menu;
            if (!permissionList || permissionList.length == 0) {
              notification.error({message: '系统提示', description: '用户未授权，请联系管理员', duration: 4});
              postAction(SysLoginUrl.logout);// 退出
              next({path: loginRouterPath, query:{redirect:to.fullPath}});//
              return;
            }
            store.commit("SET_PERMISSIONLIST", res.result.menu);
            store.commit("SET_AUTH", res.result.auth);
            let addRouter = [{
              name:'_',
              path: '/',
              redirect: permissionList[0].path,
              component: resolve => require(['../components/layouts/TabLayout'], resolve),
              meta: {
              },
              
              children: [
                ...generateChildRouters(permissionList),
                {path:'/**', component:resolve => require(['../views/exception/404'], resolve)}
              ]

            }];
            router.addRoutes(addRouter);
            let redirect = decodeURIComponent(from.query.redirect || to.path);
            if(redirect == "" || redirect == "/"){
              next({path: permissionList[0].path})
              return;
            }
            if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({...to, replace: true})
            } else {
              // 跳转到目的路由
              next({path: redirect});
            }
          });
      },
        err=>toLogin(to,from, next))
    .catch(e=>toLogin(to,from, next));
}

// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start(); // 进度条;
  let toPath = to.path;
  // 白名单 不拦截， 登录页不拦截
  if (whiteRouterPath.indexOf(toPath) !== -1) {
    next();
    return;
  }
  addRouter(to, from, next);
});

/**
 * 路由后设置locationTo 当前路由url
 */
router.afterEach((to) => {
  NProgress.done() // finish progress bar
});
export default router;